<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Simple URL content fetcher
 * 
 * Caches results in memory.
 */
class metaextractor_UrlContentFetcher
{
	protected $config = null;
	// URL content cache, key is a URL, value is a UrlContent or Exception object
	protected $urls = array();
	
	/**
	 * Create a new UrlContentFetcher instance.
	 * @param array $config Meta extractor config
	 */
	public function __construct($config)
	{
		$this->config = $config;
	}
	
	/**
	 * Fetch the content of a URL, returns a cached version if available. 
	 * @param string $url URL
	 * @return metaextractor_UrlContent URL content object
	 * @throws metaextractor_exception_Exception
	 */
	public function getUrlContent($url)
	{
		if(!isset($urls[$url]))
		{
			// no cached version available, fetch the content
			try
			{
				$urls[$url] = new metaextractor_UrlContent($this->config, $url);
			}
			catch(metaextractor_exception_Exception $exception)
			{
				// exception occurred, store the exception
				$urls[$url] = $exception;
			}
		}
		
		if($urls[$url] instanceof metaextractor_exception_Exception)
		{
			// cache contains an exception, rethrow it
			throw $urls[$url];
		}
		else
		{
			// cache contains content, return it
			return $urls[$url];
		}
	}
}